<template>
    <el-upload
        :action="uploadHttp"
        :auto-upload="true"
        :limit="limitSize"
        :show-file-list="true"
        :file-list="[uploadFile]"
        :headers="{ token: getToken() }"
        :on-success="uploadSuccess"
        :disabled="localDisabled"
        :on-exceed="overLimit"
    >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    </el-upload>
</template>

<script>
export default {
    name: 'Upload',
    props: {
        uploadFile: {
            type: Object
        },
        disabledUpload: {
            type: Boolean,
            default: false
        },
        limitSize: {
            type: Number,
            default: 5
        }
    },
    data() {
        return {
            uploadHttp: '/api/attachment/uploadFiles',
            fileUpload: [],
            localUploadFile: {},
            localDisabled: false
        };
    },
    watch: {
        uploadFile(n) {
            if (n) {
                console.log('localUploadFile', n);
                this.localUploadFile = n;
            }
        },
        disabledUpload(n) {
            if (n) {
                this.localDisabled = n;
            }
        }
    },
    methods: {
        // 上传成功
        uploadSuccess(response, file, fileList) {
            console.log(response, file, fileList);
            this.localUploadFile.fileId = response;
            //双向同步到父组件
            this.$emit('update:uploadFile', this.localUploadFile);
        },
        getToken() {
            let result = sessionStorage.getItem('token');
            return result;
        },
        remove(file) {
            console.log('删除文件', file);
            this.localUploadFile.fileId = null;
            //双向同步到父组件
            this.$emit('update:uploadFile', this.localUploadFile);
        },
        /**
         * 文件数量超出以后的钩子
         * files, fileList
         */
        overLimit() {
            this.$message({
                type: 'warning',
                message: '超过最大上传数量'
            });
        }
    }
};
</script>

<style scoped></style>
